<template>
  <div>
    <el-form
      ref="form1"
      style="padding-top: 20px;"
      label-width="120px"
      :model="models"
      :rules="rules"
      class="demo-form-inline"
    >
      <el-row>
        <el-col :span="7" :offset="1">
          <el-form-item label="数据库节点：" prop="model.databaseId">
            <el-select v-model="models.model.databaseId" placeholder="请选择">
              <el-option
                v-for="item in controlData.databaseOptions"
                :key="item.databaseId"
                :label="item.name"
                :value="item.databaseId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="类 型：" prop="model.tableType">
            <el-select v-model="models.model.tableType" @change="selectTableType">
              <el-option
                v-for="item in controlData.tableTypeOptions"
                :key="item.key"
                :label="item.key"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="版 本：" prop="model.version">
            <el-input type="text" name="version" v-model="models.model.version" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7" :offset="1">
          <el-form-item label="名 称：" prop="model.name">
            <el-input type="text" name="name" v-model="models.model.name" />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="编 码：" prop="model.code">
            <el-input type="text" name="code" v-model="models.model.code" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="默认排序列：" prop="model.sortColumn">
            <el-input
              type="text"
              name="sortColumn"
              v-model="models.model.sortColumn"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7" :offset="1">
          <el-form-item label="扩展1：" prop="model.reserve1">
            <el-input type="text" name="reserve1" v-model="models.model.reserve1" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="扩展2：" prop="model.reserve2">
            <el-input type="text" name="reserve2" v-model="models.model.reserve2" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="扩展3：" prop="model.reserve3">
            <el-input type="text" name="reserve3" v-model="models.model.reserve3" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="models.model.tableType === 'SQL'">
        <el-divider></el-divider>
        <el-col :span="20">
          <el-form-item label="SQL：" prop="model.inSql">
            <el-input type="textarea" :rows="4" v-model="models.model.inSql"></el-input>
            <ul>
              <li>如果SQL的执行结果为NULL，则无法解析出字段</li>
              <li>当多表查询时，多表之间相同的字段会有歧义，这也会导致解析字段失败，建议在SELECT中给字段起别名</li>
            </ul>
          </el-form-item>
        </el-col>
        <el-col :span="4" style="padding-left: 20px;">
          <el-button type="primary" @click="sqlAnalyze">SQL解析</el-button>
        </el-col>
      </el-row>

    </el-form>
    <el-row style="background-color: #d3dce6; padding: 6px;">
      <el-col :span="6">
        <el-row>
          <el-col>
            <span style="font-weight: 900;font-size: 19px;margin-left: 18px;">
              <i class="el-icon-present"></i>列管理
            </span>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="18">
        <el-row type="flex" justify="end">
          <el-col :span="24" style="text-align: right;">
            <el-button-group v-if="models.model.tableType === 'TABLE'">
              <el-button size="medium" @click="mapFromDb" icon="el-icon-edit" type="warning">从数据库读取</el-button>
              <el-button
                size="medium"
                @click="addTableColumn"
                icon="el-icon-plus"
                type="primary"
              >新增列</el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>从数据库读取数据完毕，是否保存数据？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭，稍后自行保存</el-button>
        <el-button type="primary" @click="mapSuccess">保存</el-button>
      </span>
    </el-dialog>
    <el-form ref="fromaData" :model="models">
      <el-table :header-cell-style="{'text-align':'center'}" :data="models.columns">
        <el-table-column prop="name" label="名称">
          <template slot-scope="scope">
            <el-form-item :prop="'columns.' + scope.$index + '.name'" :rules="rules.name" class="margin-bottom-0">
              <el-input placeholder="请输入名称" type="text" v-model="scope.row.name" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="编码">
          <template slot-scope="scope">
            <el-form-item :prop="'columns.' + scope.$index + '.code'" :rules="rules.code" class="margin-bottom-0">
              <el-input placeholder="请输入编码" type="text" v-model="scope.row.code" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="dataType" label="数据类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.dataType" placeholder="请选择">
              <el-option
                v-for="item in controlData.dataTypeOptions"
                :key="item.value"
                :label="item.key"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="dataLength" label="数据长度">
          <template slot-scope="scope">
            <el-form-item
              :prop="'columns.' + scope.$index + '.dataLength'"
              :rules="rules.dataLength"
              class="margin-bottom-0"
            >
              <el-input placeholder="请输入数据长度" type="text" v-model="scope.row.dataLength" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="isAllowNull" label="是否允许空">
          <template slot-scope="scope">
            <el-switch name="isAllowNull" v-model="scope.row.isAllowNull" :width="50" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="isEnabled" label="是否启用">
          <template slot-scope="scope">
            <el-switch :width="50" name="isEnabled" v-model="scope.row.isEnabled" />
          </template>
        </el-table-column>
        <el-table-column prop="primaryKeyType" label="主键类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.primaryKeyType">
              <el-option
                v-for="item in controlData.primaryKeyTypeOptions"
                :key="item.value"
                :label="item.key"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="indexType" label="索引类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.indexType">
              <el-option
                v-for="item in controlData.indexKeyTypeOptions"
                :key="item.value"
                :label="item.key"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="foreignTable" label="关联外键表">
          <template slot-scope="scope">
            <el-input type="text" name="foreignTable" v-model="scope.row.foreignTable" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序">
          <template slot-scope="scope">
            <el-form-item :prop="'columns.' + scope.$index + '.sort'" :rules="rules.sort" class="margin-bottom-0">
              <el-input placeholder="请输入排序" type="text" v-model="scope.row.sort" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="defaultValue" label="默认值">
          <template slot-scope="scope">
            <el-input type="text" name="defaultValue" v-model="scope.row.defaultValue" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button slot="reference" type="danger" @click="removeColumn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
import _ from "lodash";
import request from "@/utils/request";

export default {
  name: "smart-table-create",
  props: {
    models: Object,
    controlData: Object,
  },
  data() {
    return {
      dialogVisible: false,
      rules: {
        "model.version": [
          { required: true, message: "请输入版本", trigger: "change" },
        ],
        "model.name": [
          { required: true, message: "请输入名称", trigger: "change" },
        ],
        "model.code": [
          { required: true, message: "请输入编码", trigger: "change" },
        ],
        "model.sortColumn": [
          { required: true, message: "请输入默认排序列", trigger: "change" },
        ],
        name: [{ required: true, message: "名称为必填", trigger: "blur" }],
        code: [{ required: true, message: "编码为必填", trigger: "blur" }],
        dataLength: [
          { required: true, message: "数据长度为必填", trigger: "blur" },
        ],
        sort: [{ required: true, message: "排序为必填", trigger: "blur" }],
      },
    };
  },
  methods: {
    selectTableType(e) {
      this.models.columns = [];
      if (e === "SQL") {
        this.rules['model.inSql'] = [{ required: true, message: "请输入SQL", trigger: "blur" }]
      } else {
        this.rules['model.inSql'] = [{}]
      }
    },
    sqlAnalyze: function() {
      let sql = this.models.model.inSql;
      let databaseId = this.models.model.databaseId;
      if (!databaseId) {
        this.$message("请选择数据库节点");
        return;
      }
      if (!sql) {
        this.$message("请输入SQL");
        return;
      }
      request({
       headers: { "Content-Type": "application/json" },
       url: "/smartform/smartTable/sql/analysis",
       method: "post",
       data: {
         sql: sql,
         databaseId: databaseId
       }
      }).then((response) => {
        const { success, message, parameters } = response;
        if (success) {
          this.models.columns = [];
          parameters.columns.forEach(c => {
            this.models.columns.push(c);
          });
        } else {
          this.$message.error(message);
        }
      })
    },
    addTableColumn: function () {
      this.models.columns.push(
        _.extend({}, this.controlData.column, {
          isEnabled: true,
          primaryKeyType: "NONE",
          indexType: "NONE",
        })
      );
    },
    removeColumn: function (d) {
      this.$confirm("确定要删除此列吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.models.columns.remove(d);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    mapFromDb: function () {
      if (!this.models.model.code) {
        this.$message("请填写编码/表名");
        return;
      }
      if (!this.models.model.databaseId) {
        this.$message("请选择数据库节点");
        return;
      }
      this.$confirm(
        "如果数据库中已有列数据，本操作将不会清空过往数据，将以编码为依据进行合并，是否确定执行?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          request({
            url: "/smartform/smartTable/mapping",
            method: "post",
            data: {
              tableId: this.models.model.tableId,
              databaseId: this.models.model.databaseId,
              code: this.models.model.code,
            },
          }).then((r) => {
            if (r && r.success) {
              this.mapInit(r);
              this.models.columns.push(
                _.extend(
                  {},
                  this.controlData.column,
                  (this.models.columns = r.parameters.columns)
                )
              );
              // this.openDialog();
            }
          });
        })
        .catch(() => {});
    },
    openDialog: function () {
      this.dialogVisible = true;
    },
    mapSuccess: function () {
      console.log(this.$parent);
      // this.save();
    },
    mapInit: function (r) {
      this.models.columns.remove(r.parameters.columns);
    },
  },
  mounted() {
    if (!this.models.model.tableType) {
      this.models.model.tableType = this.controlData.tableTypeOptions[0].value;
    }
    if (!this.models.model.databaseId) {
      this.models.model.databaseId = this.controlData.databaseOptions[0].databaseId;
    }
  },
};
</script>

<style scoped>
.margin-bottom-0 {
  margin-bottom: 0;
}
</style>
